const Service = require('egg').Service;
const {md5} = require('../utils/utils')
const DBCFG = require('../dbcfg/dbconfig')

// 初始化模型
const models = DBCFG.getModels()

class rquserService extends Service {
  async login(loginname,loginpwd) {
    
    const res = await models.rquser.findOne({
        where: {
          loginname: loginname,
          loginpwd: loginpwd
        },
        attributes: ['userid', 'loginname','nickname', 'headicon'] // 指定只查询这几个字段
      })
    if(res){
      res.lastlogin = new Date();
      console.log('update lastlogin'+res.lastlogin);
      await res.save(); //更新最后登录时间
    }  


    return res
  }
  async list(offset,limit) {
    const { count, rows } = await models.rquser.findAndCountAll({
        order: [
          ['userid', 'DESC']  // 按ID倒序排序
        ],
        offset: Number(offset),
        limit: Number(limit)
      })
    return {
      total:count,
      items:rows
    }
  }
  async detail(_userid){
    const res = await models.rquser.findOne({
        where: {
          userid: _userid
        }
      })
    return res
  }
  async add(objData) {
    objData.loginpwd = md5(objData.loginpwd); //注册阶段将密码加密
    objData.regtime = new Date();
    const res = await models.rquser.create(objData)
    return res
  }

  async del(_userid){
    var obj = await models.rquser.findOne({
        where: {
          userid: _userid
        }
      })
    if(!obj){

      return {
        code:400,
        msg:'数据不存在'
      }
    } else {
      const res = await models.rquser.destroy({
        where: {
          userid: _userid
        }
      })
      return {
        code:200,
        msg:'删除成功'
      }
    }
  }
  
  async update(objData){
    var _userid = objData.userid;
    
    var obj = await models.rquser.findOne({
        where: {
          userid: _userid
        }
      })
    if(!obj){
      return {
        code:400,
        msg:'数据不存在'
      }
    }

    const res = await models.rquser.update(objData,{
      where: {
        userid: _userid
      }
    })
    return res;

  }

}

module.exports = rquserService;